//在要使用服务的页面
"use strict";
const chooseLocation = requirePlugin('chooseLocation');
let db = wx.cloud.database()
let _ = db.command
let OPENID = ''
let KEY = ''
let T = ''
let page = 1
let haveadd = 0
let havetraverse = 0
let AllGoodsNum = 0
let Address =  ''
let province = ''
let city = ''
let district = ''
let Alladdress = ''
let longitude = '' //经度
let latitude = '' //纬度
let userlatitude = ''
let userlongtitude = ''
let S = 0
let dbc =  wx.cloud.database().collection('Address')
var allGoods = []
let serachGoods = []
Page({
    data:{
      address:Address,
      list:[],
      IMG:[],
      IMGlist:[],
      locationName: "",
      key:null,
      banner:[]
    },
    onLoad(){
     page = 0
     this.getopenid()
    //  this.getLL()
     this.getBannerImg()
     this.getIMGList()
     this.getadd()   //云函数获取地址

     //text
   },
   onShow(){
    this.onLoad()
   },
   getBannerImg(){
    wx.cloud.database().collection('banner').get()
    .then(res=>{
      console.log('获取主页广告图成功',res.data[0])
     this.setData({
       banner:res.data[0].bannerIMG
     })
    })
    .catch(err=>{
     console.log('获取主页广告图失败',err)
    })
   },
   //1获取地址
   getadd(){
    wx.cloud.callFunction({
      name:'getAddress',
    })
    .then(res=>{
      console.log('res:',res)
      if(res.result.data.length == 0){
        wx.showToast({
          title: '请先选择您的位置',
          icon:'none',
         })
        }else{
     Address = res.result.data[0].address
     console.log('云函数获取地址成功：',Address)
     userlatitude = res.result.data[0].latitude
     userlongtitude = res.result.data[0].longitude
     console.log('云函数获取userlatitude成功：',userlatitude)
     console.log('云函数获取userlongtitude成功：',userlongtitude)
      province = res.result.data[0].province
      city = res.result.data[0].city
      district = res.result.data[0].district
     this.setData({
       locationName: Address?Address: ""
     })
    }
    this.ComparedAddress(province,city,district)
    // this.getLL()
    })
    .catch(err=>{
      console.log('云函数获取地址失败：',err)
    })
   },
   //2根据地址初次筛选商品
   ComparedAddress(province,city,district){
     wx.cloud.callFunction({
       name:'ComparedAddress',
       data:{
        province:province,
        city:city,
        district:district
       }
     })
     .then(res=>{
       console.log('---------首页所有商品获取成功----------:',res)
       allGoods = res.result
       this.getSkip(allGoods,page,havetraverse)
     })
   },
   //3判断是否到底，否的话分页加载商品，一次渲染20条
   IsOver(goods,havetraverse){
    console.log('---------------------')
    console.log('havetraverse',havetraverse)
    console.log('goods.length:',goods.length)
    console.log('---------------------')
    if(havetraverse==goods.length){
      console.log('if判断执行了')
      wx.showToast({
        title: '已经到达底部',
        icon:'none'
      })
     } else {
      this.getSkip(allGoods,havetraverse)
     }
   },
   //4分页加载商品
   getSkip(goods,loaded){
    AllGoodsNum = goods.length
    console.log('AllGoodsNum:',AllGoodsNum)
    if(loaded!=AllGoodsNum){
      console.log('havetraverse=AllGoodsNum')
    }
    if(havetraverse!=AllGoodsNum){
      // console.log('for循环执行了')
     for (let index = havetraverse; index < goods.length; index++) {
       const element = goods[index];
       this.getDistance(userlatitude,userlongtitude,element.latitude,element.longitude)
       if(S<=5){
       this.setData({
         list:this.data.list.concat(element)
       })
       haveadd++
      }
      havetraverse++
      if(haveadd==(page+1)*10)
      {
        console.log('数据到达10条，跳出')
        break
      }
      console.log('-------------------------------')
      console.log('已渲染出的的haveadd:',haveadd)
      console.log('数据已遍历的havetraverse:',havetraverse)
      console.log('-------------------------------')
     }
   }
   },
   //下拉触底
   onReachBottom(){
    console.log('---------------触底执行了----------------')
    if(havetraverse==AllGoodsNum){
      wx.showToast({
        title: '已经到达底部',
        icon:'none'
      })
    } else {
      page++
      console.log('---------------触底判断执行了----------------')
      this.getSkip(allGoods,havetraverse)
    }
    console.log('渲染的页面是：',page)
  },
   //---------------------------------
 Rad: function(d) { //根据经纬度判断距离
    return d * Math.PI / 180.0;
},
getDistance: function(lat1, lng1, lat2, lng2) {
    // lat1用户的纬度
    // lng1用户的经度
    // lat2商家的纬度
    // lng2商家的经度
    var radLat1 = this.Rad(lat1);
    var radLat2 = this.Rad(lat2);
    var a = radLat1 - radLat2;
    var b = this.Rad(lng1) - this.Rad(lng2);
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378.137;
    s = Math.round(s * 10000) / 10000;
    S = Math.round(s * 10000) / 10000
    s = s.toFixed(2) + 'km' //保留两位小数
    S = S.toFixed(2)
    console.log('经纬度计算的距离:' + s)
    return s
},
   getIMGList(){
     wx.cloud.database().collection('ICON').doc('b69f67c06315e72514603038b8076')
     .get()
     .then(res=>{
       this.setData({
         IMG:res.data.img
       })
       console.log('图标获取成功：',res)
     })
     .catch(err=>{
      console.log('图标获取失败：',err)
    })
   },
   onShow: function () {
    // 从地图选点插件返回后，在页面的onShow生命周期函数中能够调用插件接口，取得选点结果对象
    // 如果点击确认选点按钮，则返回选点结果对象，否则返回null
    const location = chooseLocation.getLocation();
    if(location){
      Address=location.name
      province = location.province
      city = location.city
      district = location.district
      Alladdress = location.address
      longitude= location.longitude
      latitude = location.latitude
        this.setData({
            locationName: location.name?location.name : ""
        });
        this.getAddress()
    }

    wx.switchTab({
      url: '/pages/home/home',
    })
},
getAddress(){
 let ID = ''
 dbc.where({
   openid:OPENID
 })
 .get()
 .then(res=>{
  console.log('地址查询成功',res)
  if(Object.keys(res.data).length == 0)
  {
  //无数据并添加地址数据
  console.log('地址查询成功,无数据并进行添加')
  this.addAddress()
}else{
  //有数据并修改地址数据
  console.log('ID:',res.data[0]._id)
  ID = res.data[0]._id
  console.log('ID:',ID)
  this.changeAdderss(ID)
}
 })
 .catch(err=>{
   console.log('地址查询失败',err)
 })
},
//添加地址
addAddress(){
  wx.cloud.database().collection('Address')
  .add({
    data: {
      openid:OPENID,
      address:Address,
      province:province,
      city:city,
      district:district,
      Alladdress:Alladdress,
      longitude:longitude, //经度
      latitude:latitude  //纬度
     }
  })
  .then(res=>{
    console.log('地址为空添加地址成功',res)
    this.onLoad()
  })
  .catch(err=>{
    console.log('地址为空添加地址失败',err)
  })
},

//修改地址
changeAdderss(ID){
  console.log('地址不为空修改地址')
  dbc.doc(ID)
  .update({
    data:{
      address:Address,
      province:province,
      city:city,
      district:district,
      Alladdress:Alladdress,
      longitude:longitude, //经度
      latitude:latitude  //纬度
   }
  })
  .then(res=>{
    console.log('地址不为空修改地址成功',res)
    this.onLoad()
  })
  .catch(err=>{
    console.log('地址不为空修改地址失败',err)
  })
},
//显示地图
showMap() {
    //使用在腾讯位置服务申请的key（必填）
    const key = "CZYBZ-X53KJ-FB5F4-FAMID-TUSKT-O2FB7"; 
    //调用插件的app的名称（必填）
    const referer = "好邻宝"; 
    wx.navigateTo({
        url: 'plugin://chooseLocation/index?key=' + key + '&referer=' + referer
    });
},
 //功能页
    goFunction(Type1,Type2){
      wx.navigateTo({
        url: '/pages/function/function?type1='+Type1+'&type2='+Type2+'&userlatitude='+userlatitude+'&userlongtitude='+userlongtitude,
      })
      console.log('成功跳转到功能页面，携带的type值为：',Type1,Type2)
    },
    type1(){ this.goFunction(1,9)},
    type2(){ this.goFunction(10,13)},
    type3(){ this.goFunction(14,17)},
    type4(){ this.goFunction(18,21)},
    type5(){ this.goFunction(22,27)},
    type6(){ this.goFunction(28,30)},
    type7(){ this.goFunction(31,34)},
    type8(){ this.goFunction(35,40)},
    type9(){ this.goFunction(41,44)},
    type10(){ this.goFunction(45,47)},
    type11(){ this.goFunction(48,50)},
    type12(){ this.goFunction(51,52)},

    //获取openid
   getopenid(){
          wx.cloud.callFunction({
            name:'getOPENID'
          })
          .then(res=>{
            console.log('成功获取openID',res)
            OPENID = res.result.openid
            this.addUserProfile()
            this.addOrder()
            this.addShoppingCart()
          })
  },
  getKey(e){
    console.log('搜索的内容是：',e.detail.value)
    this.setData({
      key:e.detail.value
    })
    KEY = e.detail.value
  },
  goSearch(e){
    if(!this.data.key){
      wx.showToast({
        title: '请输入内容',
        icon:'none'
      })
    }else{
    console.log('点击了搜索,跳转页面携带的KEY为:',KEY)
    wx.navigateTo({
      url: '/pages/Search/Search?SearchKey='+KEY+'&T='+0+'&address='+Address+'&array='+encodeURIComponent(JSON.stringify(allGoods))+'&userlatitude='+userlatitude+'&userlongtitude='+userlongtitude,
    })
  }
  },
   goDetail(e){
     console.log('点击了商品详情页',e.currentTarget.dataset.id)
     wx.navigateTo({
       url: '/pages/details/details?id='+e.currentTarget.dataset.id,
     })
   },
   //新用户添加个人信息
   addUserProfile() {
    wx.cloud.database().collection('user-information')
    .where({
      _openid:OPENID
    })
    .get()
    .then(res=>{   
    if (Object.keys(res.data).length == 0){
      console.log("用户信息为空")
      wx.cloud.database().collection('user-information')
      .add({
        data: {
         openid:OPENID,
         NAME:'微信用户',
         image:'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0',
         information:'无简介',
         sex:''
        }
      })
      .then(res=>{
        console.log('新默认用户录入成功',res)
      })
      }else{
      console.log("用户信息不为空")
      }
    })
  },
  //新用户添加订单信息
  addOrder(){
    console.log('OPENID',OPENID)
    wx.cloud.database().collection('All-Orders')
    .where({
      openid:OPENID
    })
    .get()
    .then(res=>{   
    if (Object.keys(res.data).length == 0){
      console.log('Object.keys(res.data).length:',Object.keys(res.data))
      console.log("用户订单信息为空")
      let SellNum = 0
      let NotNum = 0
      let UnusedNum = 0
      var SellID = []
      var NotID = []
      var UnusedID = []
      var Sell = {SellID,SellNum}
      var Not = {NotID,NotNum}
      var Unused = {UnusedID,UnusedNum}
      wx.cloud.database().collection('All-Orders')
      .add({
        data: {
         openid:OPENID,
         Sell:Sell,
         Not:Not,
         Unused:Unused
        }
      })
      .then(res=>{
        console.log('新默认用户订单信息录入成功',res)
      })
      .catch(err=>{
        console.log('新默认用户订单信息录入失败',err)
      })
      }else{
      console.log("用户订单信息不为空")
      }
    })
  },
  // 新用户添加购物车
  addShoppingCart(){
    wx.cloud.database().collection('shopping-cart')
    .where({
      openid:OPENID
    })
    .get()
    .then(res=>{   
    if (Object.keys(res.data).length == 0){
      console.log('Object.keys(res.data).length:',Object.keys(res.data))
      console.log("用户购物车信息为空")
      var goods = []
      wx.cloud.database().collection('shopping-cart')
      .add({
        data: {
         openid:OPENID,
         goods:goods,
        }
      })
      .then(res=>{
        console.log('新默认用户购物车信息录入成功',res)
      })
      .catch(err=>{
        console.log('新默认用户购物车信息录入失败',err)
      })
      }else{
      console.log("用户购物车信息不为空")
      }
    })
  }

  })